package com.lagou.deu.mvcframework.servlet;

import com.lagou.deu.mvcframework.servlet.annotataions.*;
import com.lagou.deu.mvcframework.servlet.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LaDispatcharServlet extends HttpServlet {
    private Properties properties = new Properties();

    private List<String> classNames = new ArrayList<String>();// 用于存储类名

    private Map<String,Object> ioc = new HashMap<>();
    //用于存储url与method  参数绑定信息
    private  List<Handler> handlerMapping = new ArrayList<>();

    @Override
    public void init(ServletConfig config) throws ServletException {

        // 1.加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));
        // 2.扫描相关的类
        doScan(properties.getProperty("scanPackage"));
        // 3.初始化bean
        doInstance();
        // 4.依赖注入
        doAutoWired();
        // 5.构造HandlerMappging处理器映射器
        initHandlerMapping();
        System.out.println("MVC初始化完成。。。");
        // 等待请求进入处理请求
    }
    /**
     *构造HandlerMapping
     *  目的：将url与method建立关联
      */

    private void initHandlerMapping() {
        if(ioc.isEmpty()) return;
        for(Map.Entry<String,Object> entry:ioc.entrySet()){
            //获取当前遍历的对象class类型
            Class<?> aClass = entry.getValue().getClass();
            if(!aClass.isAnnotationPresent(LagouController.class)){//只获取被LagouController修饰的类
                continue;
            }
            String baseUrl = "";
            if(aClass.isAnnotationPresent(LagouRequestMapping.class)){
                //获取类上被@LagouRequestMapping修饰的类
                LagouRequestMapping annotation = aClass.getAnnotation(LagouRequestMapping.class);
                baseUrl = annotation.value(); //   /demo
            }
            //获取method方法
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if(!method.isAnnotationPresent(LagouRequestMapping.class)){
                    continue;
                }
                LagouRequestMapping annotation = method.getAnnotation(LagouRequestMapping.class);
                String url = baseUrl+annotation.value();// /demo/get
                //把method所有信息及url封装为一个handler
                Handler handler = new Handler(entry.getValue(), method, Pattern.compile(url));
                // 计算方法参数的位置信息  public void get(HttpServletRequest request, HttpServletResponse response, String name)
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    Parameter parameter = parameters[i];
                    // 如果是request 和response对象，那么参数名写HttpServletRequest   HttpServletResponse
                    if(parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class){
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),i);
                    }else {//业务参数   string name
                        handler.getParamIndexMapping().put(parameter.getName(),i);// <name,2>
                    }
                }
                handlerMapping.add(handler);//缓存到list中
            }

        }
    }
    // 依赖注入
    private void doAutoWired() {
        if(ioc.isEmpty()) return;
        //遍历IOC  map 获取对象的所有属性判断是否有@Autowired修饰，如果有需要进行依赖注入
        for(Map.Entry<String,Object> entry:ioc.entrySet()){
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            for (int i = 0; i < declaredFields.length; i++) {
                Field declaredField = declaredFields[i];
                //判断是否@LagouAutowired修饰
                if(!declaredField.isAnnotationPresent(LagouAutowired.class)){
                    continue;
                }

                //有修饰
                LagouAutowired annotation = declaredField.getAnnotation(LagouAutowired.class);
                String value = annotation.value();
                if("".equals(value.trim())){//trim() 去空格
                    //没有具体的id则获取当前字段类型注入
                    value  = declaredField.getType().getName();// 由于IOC容器中存入了权限定的service  id 所以可以直接通过他获取
                }
                // 暴力访问
                declaredField.setAccessible(true);
                try {
                    declaredField.set(entry.getValue(),ioc.get(value));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    // 初始化bean
    private void doInstance() {
        try {
            if(classNames.size() == 0) return;
            for (int i = 0; i <classNames.size() ; i++) {
                String classname = classNames.get(i);//com.lagou.edu.controller.DemoController
                Class<?> aClass = Class.forName(classname);
                // 区分@Controller 和@Service    @Service不写value时使用当前类名， Controller不做处理直接去类名
                if(aClass.isAnnotationPresent(LagouController.class)){
                    String simpleName = aClass.getSimpleName();//DemoController
                    String name = lowerFirst(simpleName);
                    Object o = aClass.newInstance();
                    ioc.put(name,o);
                }else if(aClass.isAnnotationPresent(LagouService.class)){
                    //判断注解是否有value值
                    LagouService annotation = aClass.getAnnotation(LagouService.class);
                    if(!annotation.value().equals("")){
                        ioc.put(annotation.value(),aClass.newInstance());// 直接作为id存入map中
                    }else{
                        String beanName = lowerFirst(aClass.getSimpleName());
                        ioc.put(beanName,aClass.newInstance());
                    }
                    // service层通常是面向接口开发，因此需要获取接口名在存入IOC中
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (int j = 0; j < interfaces.length; j++) {
                        Class<?> anInterface = interfaces[j];
                        ioc.put(anInterface.getName(),aClass.newInstance());//以接口的权限定类名放入IOC中
                    }
                }else{
                    continue;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    // 首字母转小写
    private String lowerFirst(String simpleName) {
        char[] chars = simpleName.toCharArray();
        if('A'<=chars[0] && chars[0] >= 'Z'){
            chars[0] +=32;
        }
        return simpleName.valueOf(chars);
    }

    // 扫描类
    private void doScan(String scanPackage) {
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();//当前项目的所在磁盘
        String scanPackagePath = path+scanPackage.replaceAll("\\.","/");//com/lagou/edu
        File file = new File(scanPackagePath);
        File[] files = file.listFiles();
        for (File file1 : files) {
            if(file1.isDirectory()){
                // 递归
                doScan(scanPackage+"."+file1.getName());//com.lagou.deu.controller
            }else if(file1.getName().endsWith(".class")){
                String className = scanPackage+"."+ file1.getName().replaceAll(".class","");
                classNames.add(className);
            }
        }
    }

    // 加载配置文件
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 权限校验   获取@Security中value与url username对比  匹配放行
     * @param username
     * @return
     */
    private Boolean doSecurity(String username){
        for(Map.Entry<String,Object> entry:ioc.entrySet()){
            Class<?> aClass = entry.getValue().getClass();//获取IOC类
            if(aClass.isAnnotationPresent(Security.class)){
                Security annotation = aClass.getAnnotation(Security.class);
                String[] value = annotation.value();
                for (String s : value) {
                    if(s.equals(username)){ // 匹配放行
                        return true;
                    }
                }
                return false;
            }
            Method[] methods = aClass.getMethods();// 注解在方法上进行比较
            for (Method method : methods) {
                if(method.isAnnotationPresent(Security.class)){
                    Security annotation = method.getAnnotation(Security.class);// 获取方法上的注解
                    String[] value = annotation.value();
                    for (String s : value) {
                        if(s.equals(username)){
                            return true;
                        }
                    }
                    return false;
                }
            }
        }
        return false;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理请求 ，根据url找到对应的handler方法进行调用
        // 根据请求获取请求的handler
        Handler handler = getHandler(req);
        if(handler == null){
            resp.getWriter().write("404 not found");
            return;
        }
        // 权限校验
        String username = req.getParameter("username");
       if(!doSecurity(username)){
           resp.getWriter().write("No permission!!!");
           return;
       }
        //参数绑定
        //获取handler方法中所有的参数类型长度  目前方法就三个
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        // 以handler方法中多少参数来创建参数数组 ，该数据需要传出反射中去调用的
        Object[] paraValues = new Object[parameterTypes.length];
        // 以下是向参数数组中传值，并且要保证参数的顺序要与handler方法中的参数顺序一致
        Map<String, String[]> parameterMap = req.getParameterMap(); // 获取业务参数
        for(Map.Entry<String,String[]> entry:parameterMap.entrySet()){//遍历前端传过来的参数,
            String value = StringUtils.join(entry.getValue(), ',');// 如同1,2
            //如果参数和方法上的参数没匹配上则跳过
            if(!handler.getParamIndexMapping().containsKey(entry.getKey())){
                continue;
            }
            //如果匹配上了，获取索引位置，对应的参数放入paraValues中
            Integer index = handler.getParamIndexMapping().get(entry.getKey());//
            paraValues[index] = value;
        }
        Integer requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paraValues[requestIndex] = req;
        Integer responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paraValues[responseIndex] = resp;
        //最终调用method的invoke
        try {
            handler.getMethod().invoke(handler.getController(),paraValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private Handler getHandler(HttpServletRequest req) {
        if(handlerMapping.isEmpty()) return null;
        String url = req.getRequestURI();
        for(Handler handler : handlerMapping){
            Matcher matcher = handler.getPattern().matcher(url);//根据路径去匹配handler
            if(!matcher.matches()) continue;
            return handler;
        }
        return null;
    }
}
